package com.yy.permissions_general.module.system.user.controller;


import cn.hutool.core.util.ObjectUtil;
import com.yy.permissions_general.base.controller.BaseController;
import com.yy.permissions_general.common.config.session.HttpSessionContext;
import com.yy.permissions_general.common.config.session.HttpSessionContextHolder;
import com.yy.permissions_general.common.constant.SystemConstant;
import com.yy.permissions_general.module.system.user.entity.SysOnlineUser;
import com.yy.permissions_general.module.system.user.entity.User;
import com.yy.permissions_general.utils.DateUtil;
import com.yy.permissions_general.utils.ResultUtil;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
* @Description: 在线用户控制器
* @Author: YY
* @Date: 2021/12/5
*/
@RestController
@RequestMapping("/online")
public class OnlineController extends BaseController {

    @Resource
    private SessionRegistry sessionRegistry;

    /**
    * @Description: 在线用户列表
    * @Author: YY
    * @Date: 2021/12/5
    */
    @GetMapping("/list")
    public ResultUtil list(String userName) {
        List<Object> allPrincipalsUser = sessionRegistry.getAllPrincipals();
        List<SysOnlineUser> onlineUser = new ArrayList<>();
        for (Object obj : allPrincipalsUser) {
            User user = (User) obj;
            if (ObjectUtil.isNotEmpty(userName)){
                if (!user.getUsername().equals(userName)){
                    continue;
                }
            }
            SysOnlineUser sysOnlineUser = new SysOnlineUser();
            sysOnlineUser.setUserId(user.getId());
            sysOnlineUser.setUsername(user.getUsername());
            sysOnlineUser.setAccount(user.getAccount());
            sysOnlineUser.setLastTime(user.getLastTime());
            sysOnlineUser.setOnlineTime(DateUtil.getDateMin(user.getLastTime()).get("min") + "分钟");
            onlineUser.add(sysOnlineUser);
        }
        return ResultUtil.buildPagination(onlineUser);
    }



    /**
    * @Description: 踢出用户（下线）
    * @Author: YY
    * @Date: 2021/12/5
    */
    @DeleteMapping("/remove/{onlineId}")
    @ResponseBody
    public ResultUtil remove(@PathVariable Integer onlineId) {
        // 从sessionRegistry中获取所有的用户信息
        List<Object> principals = sessionRegistry.getAllPrincipals();
        for (Object principal : principals) {
            User userDetails = (User) principal;
            if (onlineId == userDetails.getId()) {
                // 不允许操作admin用户下线
                if (SystemConstant.SUPER_ADMIN.equals(userDetails.getAccount())) {
                    return ResultUtil.error("不允许操作超级管理员[admin]下线~");
                }
                for (SessionInformation sessionInformation : sessionRegistry.getAllSessions(userDetails, false)) {
                    sessionInformation.expireNow();
                    // 从sessionRegistry中清除session信息
                    sessionRegistry.removeSessionInformation(sessionInformation.getSessionId());
//                    HttpSessionContext sessionContext = HttpSessionContextHolder.currentSessionContext();
//                    // 销毁session
//                    sessionContext.getSession(sessionInformation.getSessionId()).invalidate();
                    // 从HttpSessionContext中清除session信息
                    HttpSession httpSession = HttpSessionContextHolder.currentSessionContext().getSession(sessionInformation.getSessionId());
                    HttpSessionContextHolder.currentSessionContext().removeSession(httpSession);
                }
                return ResultUtil.success(String.format("用户[%s]已下线", userDetails.getUsername()));
            }
        }
        return ResultUtil.error("用户未在线~");
    }
}
